﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net.Mail;

namespace Sustainalytics.Admin.CRMSynchronization
{
    public class EmailManager
    {
        private string _emailSubjectFile;
        private string _emailBodyFile;
        private string _QAEmail = string.Empty;
        private string _SustSupportEmail;
        private string _senderEmail;
        private string _deploymentLocation;
        private Dictionary<string, string> _placeholderDict = new Dictionary<string, string>();

        public EmailManager(string subjectFileName, string bodyFileName)
        {
            _emailSubjectFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, subjectFileName);
            _emailBodyFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, bodyFileName);

            _QAEmail = (ConfigurationManager.AppSettings["QAEmail"] ?? string.Empty).Trim();
            _SustSupportEmail = ConfigurationManager.AppSettings["SustSupportEmail"];
            _senderEmail = ConfigurationManager.AppSettings["SenderEmail"];
            _deploymentLocation = ConfigurationManager.AppSettings["DeploymentLocation"];
        }

        public void AddPlaceholderValue(string placeholder, string value)
        {
            _placeholderDict.Add(placeholder, value);
        }
        public void SendEmail()
        {
            var alertEmailMessage = new MailMessage
            {
                Subject = String.Format("{0} - {1}", _deploymentLocation, File.ReadAllText(_emailSubjectFile)),
                IsBodyHtml = true,
                From = new MailAddress(_senderEmail)
            };
            alertEmailMessage.To.Add(new MailAddress(string.IsNullOrWhiteSpace(_QAEmail) ? _SustSupportEmail : _QAEmail));
            alertEmailMessage.Body = File.ReadAllText(_emailBodyFile);
            _placeholderDict.ForEach(x => alertEmailMessage.Body = alertEmailMessage.Body.Replace(x.Key, x.Value));

            SendEmail(alertEmailMessage);
        }

        private void SendEmail(MailMessage message)
        {
            SmtpClient mailClient = new SmtpClient();
            try
            {
                mailClient.Send(message);
            }
            catch
            {
                //supress exception
            }
            finally
            {
                mailClient.Dispose();
            }
        }
    }
}
